﻿using Festival_Locator.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.AspNet.Membership.OpenAuth;
using System.Web.Security;

namespace Festival_Locator.Account
{
    public partial class Manage : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected string SuccessMessage
        {
            get;
            private set;
        }

        protected bool CanRemoveExternalLogins
        {
            get;
            private set;
        }

        public List<String> getUsers()
        {
            List<String> users = new List<String>();
            MembershipUserCollection Allusers = Membership.GetAllUsers();

            foreach (MembershipUser u in Allusers)
            {
                users.Add(u.UserName);
            }

            return users;

        }

        protected void Page_Load()
        {
            
           
            
            if (!IsPostBack)
            {
                string count = "0";
                if (Request.QueryString["id"] != null)
                    count = Request.QueryString["id"];
                if (count.Equals("1"))
                {
                    Label3.Text = "U kan uzelf niet verwijderen";
                }
                if (count.Equals("2"))
                {
                    Label3.Text = "De gebruiker is succesvol verwijderd";
                }
                // Determine the sections to render
                var hasLocalPassword = OpenAuth.HasLocalPassword(User.Identity.Name);
                setPassword.Visible = !hasLocalPassword;
                changePassword.Visible = hasLocalPassword;

                CanRemoveExternalLogins = hasLocalPassword;

                // Render success message
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Strip the query string from action
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Your password has been changed."
                        : message == "SetPwdSuccess" ? "Your password has been set."
                        : message == "RemoveLoginSuccess" ? "The external login was removed."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }

                users.DataSource = getUsers();
                users.DataBind();

                if (Page.User.IsInRole("Admins"))
                {
                    ManageUsers.Visible = true;
                }
                else
                {
                    ManageUsers.Visible = false;
                }
            }

        }

        protected void setPassword_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                var result = OpenAuth.AddLocalPassword(User.Identity.Name, password.Text);
                if (result.IsSuccessful)
                {
                    Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
                }
                else
                {
                    ModelState.AddModelError("NewPassword", result.ErrorMessage);
                }
            }
        }


        public IEnumerable<OpenAuthAccountData> GetExternalLogins()
        {
            var accounts = OpenAuth.GetAccountsForUser(User.Identity.Name);
            CanRemoveExternalLogins = CanRemoveExternalLogins || accounts.Count() > 1;
            return accounts;
        }

        public void RemoveExternalLogin(string providerName, string providerUserId)
        {
           /* var m = OpenAuth.DeleteAccount(User.Identity.Name, providerName, providerUserId)
                ? "?m=RemoveLoginSuccess"
                : String.Empty;*/
          //  Response.Redirect("~/Account/Manage" );
        }


        protected static string ConvertToDisplayDateTime(DateTime? utcDateTime)
        {
            // You can change this method to convert the UTC date time into the desired display
            // offset and format. Here we're converting it to the server timezone and formatting
            // as a short date and a long time string, using the current thread culture.
            return utcDateTime.HasValue ? utcDateTime.Value.ToLocalTime().ToString("G") : "[never]";
        }
        protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            String user = GridView2.Rows[e.RowIndex].Cells[1].Text;
            if (!user.Equals(User.Identity.Name))
            {
                Membership.DeleteUser(user);
                Response.Redirect("~/Account/Manage?id=2");
            }
            else
            {
                Response.Redirect("~/Account/Manage?id=1");
            }
            
        }
        protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lbEdit = (LinkButton)e.Row.Cells[0].Controls[0];
                lbEdit.Text = "<i class='icon-edit icon-white'></i>";
                lbEdit.BorderColor = System.Drawing.Color.Black;
                lbEdit.ForeColor = System.Drawing.Color.Red;

                LinkButton lbDelete = (LinkButton)e.Row.Cells[0].Controls[2];
                lbDelete.Text = "<i class='icon-remove icon-white'></i>";
                lbDelete.BorderColor = System.Drawing.Color.Black;
            }
        }
    }
}